document.addEventListener('DOMContentLoaded', function() {
  // ---------- 缓存DOM元素（减少重复查询） ----------
  const elements = {
    // 筛选相关
    stageFilter: document.getElementById('stage-filter'),
    typeFilter: document.getElementById('type-filter'),
    courseTypeFilter: document.getElementById('course-type-filter'),
    commonCategoryFilter: document.getElementById('common-category-filter'),
    sortOptions: document.querySelectorAll('.sort-option'),
    courseCards: Array.from(document.querySelectorAll('.course-card')),
    cardsContainer: document.querySelector('.course-cards'),
    
    // 模态框相关
    modal: {
      course: document.getElementById('courseModal'),
      edit: document.getElementById('editModal'),
      addCourse: document.getElementById('addCourseModal'),
      styleSetting: document.getElementById('styleSettingModal'),
      restore: document.getElementById('restoreModal'),
      batchDelete: document.getElementById('batchDeleteModal')
    },
    
    // 按钮相关
    customBtn: document.getElementById('customBtn'),
    saveResultBtn: document.getElementById('saveResultBtn'),
    cancelCustomBtn: document.getElementById('cancelCustomBtn'), // 取消按钮
    addCourseBtn: document.getElementById('addCourseBtn'),
    bgColorBtn: document.getElementById('bgColorBtn'),
    restoreDefaultBtn: document.getElementById('restoreDefaultBtn'),
    batchDeleteBtn: document.getElementById('batchDeleteBtn'),
    editCategoryBtn: document.getElementById('editCategoryBtn'),
    
    // 表单相关
    editForm: document.getElementById('editForm'),
    addCourseForm: document.getElementById('addCourseForm'),
    
    // 批量删除相关
    batch: {
      stageFilter: document.getElementById('batchStageFilter'),
      typeFilter: document.getElementById('batchTypeFilter'),
      courseTypeFilter: document.getElementById('batchCourseTypeFilter'),
      commonCategoryFilter: document.getElementById('batchCommonCategoryFilter'),
      deselectAllBtn: document.getElementById('deselectAll'),
      selectAllBtn: document.getElementById('selectAll'),
      customCourseSelection: document.getElementById('customCourseSelection'),
      deleteSelectedBtn: document.getElementById('deleteSelected'),
      confirmBatchDeleteBtn: document.getElementById('confirmBatchDelete')
    }
  };

  // 存储原始卡片（用于恢复默认）
  const originalCards = [...elements.courseCards];
  
  // 存储当前编辑会话开始前的状态（用于取消操作）
  let currentSessionState = {
    courseCards: [],
    styles: {
      containerBg: '',
      containerBgImage: '',
      cardStyles: []
    }
  };
  
  // 状态管理
  const state = {
    currentSort: { direction: 'desc', key: 'default' },
    isEditMode: false,
    currentEditingCard: null,
    // 保存已持久化的状态（已通过"保存结果"确认的状态）
    persistedStyles: {
      containerBg: document.querySelector('.container')?.style.backgroundColor || '',
      containerBgImage: document.querySelector('.container')?.style.backgroundImage || 'none',
      cardBorder: document.querySelector('.course-card')?.style.borderColor ?? '#90caf9',
      cardText: document.querySelector('.course-card')?.style.color ?? '#333'
    }
  };

  // ---------- 工具函数 ----------
  const utils = {
    // 通用模态框关闭函数
    closeModal(modal) {
      if (modal) modal.style.display = 'none';
    },
    
    // 通用模态框打开函数
    openModal(modal) {
      if (modal) modal.style.display = 'flex';
    },
    
    // 批量绑定事件
    bindEvents(elements, eventType, handler) {
      elements.forEach(el => el?.addEventListener(eventType, handler));
    },
    
    // 生成星星评分字符串
    generateStars(count) {
      return '★'.repeat(Math.max(0, Math.min(5, parseInt(count) || 0)));
    },
    
    // 安全获取DOM元素属性
    getElementData(el, key, defaultValue = 'all') {
      return el?.dataset[key] ?? defaultValue;
    },
    
    // 深拷贝卡片状态
    cloneCardState(card) {
      return {
        html: card.innerHTML,
        dataset: {...card.dataset},
        style: {
          backgroundColor: card.style.backgroundColor,
          backgroundImage: card.style.backgroundImage,
          borderColor: card.style.borderColor,
          color: card.style.color
        }
      };
    },
    
    // 生成唯一ID
    generateId() {
      return Date.now().toString(36) + Math.random().toString(36).substr(2, 5);
    }
  };

  // ---------- 筛选与排序功能 ----------
  const filterAndSort = {
    // 多条件筛选
    filterCards() {
      const stage = elements.stageFilter.value;
      const type = elements.typeFilter.value;
      const courseType = elements.courseTypeFilter.value;
      const commonCategory = elements.commonCategoryFilter.value;

      elements.courseCards.forEach(card => {
        const cardStage = utils.getElementData(card, 'stage');
        const cardType = utils.getElementData(card, 'type');
        const cardCourseType = utils.getElementData(card, 'courseType');
        const cardCommonCategory = utils.getElementData(card, 'commonCategory');

        const isMatch = 
          (stage === 'all' || cardStage === stage) &&
          (type === 'all' || cardType === type) &&
          (courseType === 'all' || cardCourseType === courseType) &&
          (commonCategory === 'all' || cardCommonCategory === commonCategory);

        card.style.display = isMatch ? 'block' : 'none';
      });

      this.sortCards();
    },
    
    // 排序卡片
    sortCards() {
      const displayCards = elements.courseCards.filter(card => card.style.display === 'block');
      if (displayCards.length === 0) return;

      displayCards.sort((cardA, cardB) => {
        if (state.currentSort.key === 'default') {
          // 字母排序（课程名称）
          const valA = cardA.querySelector('h3').textContent.toLowerCase();
          const valB = cardB.querySelector('h3').textContent.toLowerCase();
          return state.currentSort.direction === 'asc' 
            ? valA.localeCompare(valB) 
            : valB.localeCompare(valA);
        } else {
          // 数值排序
          const valA = parseFloat(utils.getElementData(cardA, state.currentSort.key)) || 0;
          const valB = parseFloat(utils.getElementData(cardB, state.currentSort.key)) || 0;
          return state.currentSort.direction === 'asc' ? valA - valB : valB - valA;
        }
      });

      // 批量更新DOM（减少重绘）
      const fragment = document.createDocumentFragment();
      displayCards.forEach(card => fragment.appendChild(card));
      elements.cardsContainer.appendChild(fragment);
    },
    
    // 初始化筛选排序事件
    initEvents() {
      // 筛选器事件
      utils.bindEvents(
        [
          elements.stageFilter,
          elements.typeFilter,
          elements.courseTypeFilter,
          elements.commonCategoryFilter
        ],
        'change',
        () => this.filterCards()
      );

      // 排序选项事件
      elements.sortOptions.forEach(option => {
        option.addEventListener('click', function() {
          elements.sortOptions.forEach(opt => opt.classList.remove('active'));
          this.classList.add('active');
          state.currentSort = {
            direction: this.dataset.sort,
            key: this.dataset.key
          };
          filterAndSort.sortCards();
        });
      });
    }
  };

  // ---------- 模态框功能 ----------
  const modalManager = {
    // 初始化所有模态框事件
    initEvents() {
      // 课程详情模态框
      this.bindModalEvents(
        elements.modal.course,
        document.querySelector('.close-btn'),
        () => utils.closeModal(elements.modal.course)
      );

      // 编辑模态框
      this.bindModalEvents(
        elements.modal.edit,
        [document.querySelector('.modal-close'), document.querySelector('.modal-close-btn')],
        () => {
          utils.closeModal(elements.modal.edit);
          state.currentEditingCard = null;
        }
      );

      // 添加课程模态框
      this.bindModalEvents(
        elements.modal.addCourse,
        [
          elements.modal.addCourse?.querySelector('.modal-close'),
          elements.modal.addCourse?.querySelector('.modal-close-btn')
        ],
        () => {
          utils.closeModal(elements.modal.addCourse);
          elements.addCourseForm?.reset();
        }
      );

      // 样式设置模态框
      this.bindModalEvents(
        elements.modal.styleSetting,
        [
          elements.modal.styleSetting?.querySelector('.modal-close'),
          elements.modal.styleSetting?.querySelector('.modal-close-btn')
        ],
        () => utils.closeModal(elements.modal.styleSetting)
      );

      // 恢复默认模态框
      this.bindModalEvents(
        elements.modal.restore,
        [
          elements.modal.restore?.querySelector('.modal-close'),
          elements.modal.restore?.querySelector('.modal-close-btn')
        ],
        () => utils.closeModal(elements.modal.restore)
      );

      // 批量删除模态框
      this.bindModalEvents(
        elements.modal.batchDelete,
        [
          elements.modal.batchDelete?.querySelector('.modal-close'),
          elements.modal.batchDelete?.querySelector('.modal-close-btn')
        ],
        () => utils.closeModal(elements.modal.batchDelete)
      );
    },
    
    // 绑定模态框通用事件（打开/关闭/点击外部关闭）
    bindModalEvents(modal, closeButtons, closeHandler) {
      if (!modal) return;

      // 关闭按钮事件
      if (Array.isArray(closeButtons)) {
        closeButtons.forEach(btn => btn?.addEventListener('click', closeHandler));
      } else {
        closeButtons?.addEventListener('click', closeHandler);
      }

      // 点击外部关闭
      window.addEventListener('click', (e) => {
        if (e.target === modal) closeHandler();
      });
    }
  };

  // ---------- 编辑模式功能 ----------
  const editMode = {
    // 进入编辑模式 - 保存当前状态用于取消操作
    enter() {
      // 为每个卡片添加唯一标识（如果没有）
      elements.courseCards.forEach(card => {
        if (!card.dataset.editId) {
          card.dataset.editId = utils.generateId();
        }
      });
      
      // 保存进入本次编辑会话前的状态（作为取消时的恢复点）
      this.saveCurrentSessionState();
      
      state.isEditMode = true;
      document.body.classList.add('edit-mode');
      this.toggleEditElements(true);
    },
    
    // 退出编辑模式（保存更改）
    exit() {
      // 保存当前状态作为新的持久化状态
      this.updatePersistedState();
      
      state.isEditMode = false;
      document.body.classList.remove('edit-mode');
      this.toggleEditElements(false);
    },
    
    // 取消编辑（不保存当前会话的更改，恢复到进入编辑前的状态）
    cancel() {
      // 恢复到进入本次编辑会话前的状态
      this.restoreCurrentSessionState();
      
      state.isEditMode = false;
      document.body.classList.remove('edit-mode');
      this.toggleEditElements(false);
      
      // 关闭所有可能打开的模态框
      Object.values(elements.modal).forEach(modal => {
        utils.closeModal(modal);
      });
    },
    
    // 保存当前会话状态（进入编辑模式时）
    saveCurrentSessionState() {
      const container = document.querySelector('.container');
      
      // 保存当前卡片状态
      currentSessionState.courseCards = elements.courseCards.map(card => {
        return {
          editId: card.dataset.editId,
          state: utils.cloneCardState(card)
        };
      });
      
      // 保存当前样式状态
      currentSessionState.styles = {
        containerBg: container?.style.backgroundColor || '',
        containerBgImage: container?.style.backgroundImage || '',
        cardStyles: elements.courseCards.map(card => ({
          backgroundColor: card.style.backgroundColor,
          backgroundImage: card.style.backgroundImage,
          borderColor: card.style.borderColor,
          color: card.style.color
        }))
      };
    },
    
    // 恢复到当前会话开始前的状态
    restoreCurrentSessionState() {
      const container = document.querySelector('.container');
      
      // 恢复容器样式
      if (container) {
        container.style.backgroundColor = currentSessionState.styles.containerBg;
        container.style.backgroundImage = currentSessionState.styles.containerBgImage;
      }
      
      // 恢复现有卡片的状态
      elements.courseCards.forEach(card => {
        const originalState = currentSessionState.courseCards.find(item => 
          item.editId === card.dataset.editId
        )?.state;
        
        if (originalState) {
          // 恢复卡片内容和属性
          card.innerHTML = originalState.html;
          Object.entries(originalState.dataset).forEach(([key, value]) => {
            card.dataset[key] = value;
          });
          
          // 恢复卡片样式
          card.style.backgroundColor = originalState.style.backgroundColor;
          card.style.backgroundImage = originalState.style.backgroundImage;
          card.style.borderColor = originalState.style.borderColor;
          card.style.color = originalState.style.color;
          
          // 恢复文本颜色
          card.querySelectorAll('h3, p').forEach(el => {
            el.style.color = originalState.style.color;
          });
        }
      });
      
      // 移除在本次编辑会话中添加的新卡片
      const currentEditIds = elements.courseCards.map(card => card.dataset.editId);
      const sessionEditIds = currentSessionState.courseCards.map(item => item.editId);
      
      const newEditIds = currentEditIds.filter(id => !sessionEditIds.includes(id));
      newEditIds.forEach(id => {
        const card = elements.courseCards.find(c => c.dataset.editId === id);
        if (card) {
          const index = elements.courseCards.indexOf(card);
          if (index > -1) elements.courseCards.splice(index, 1);
          card.remove();
        }
      });
      
      // 刷新筛选
      filterAndSort.filterCards();
    },
    
    // 更新持久化状态（保存结果时）
    updatePersistedState() {
      const container = document.querySelector('.container');
      
      // 更新持久化的样式状态
      if (container) {
        state.persistedStyles.containerBg = container.style.backgroundColor;
        state.persistedStyles.containerBgImage = container.style.backgroundImage;
      }
      
      // 可以在这里添加本地存储逻辑，将状态保存到localStorage
      // 例如: localStorage.setItem('courseAppState', JSON.stringify(state.persistedStyles));
    },
    
    // 显示/隐藏编辑相关元素
    toggleEditElements(show) {
      const display = show ? 'flex' : 'none';
      const inlineDisplay = show ? 'inline-block' : 'none';
      
      // 显示/隐藏取消按钮
      elements.cancelCustomBtn.style.display = display;
      
      elements.addCourseBtn.style.display = display;
      elements.bgColorBtn.style.display = display;
      elements.restoreDefaultBtn.style.display = display;
      elements.batchDeleteBtn.style.display = display;
      elements.saveResultBtn.style.display = display;
      elements.editCategoryBtn.style.display = inlineDisplay;
      
      document.querySelectorAll('.card-delete').forEach(btn => {
        btn.style.display = display;
      });
      document.querySelectorAll('.card-edit').forEach(btn => {
        btn.style.display = show ? 'block' : 'none';
      });
      
      elements.customBtn.style.display = show ? 'none' : 'flex';
    },
    
    // 初始化编辑模式事件
    initEvents() {
      // 进入编辑模式
      elements.customBtn?.addEventListener('click', () => this.enter());
      
      // 退出编辑模式（保存结果）
      elements.saveResultBtn?.addEventListener('click', () => this.exit());
      
      // 取消编辑（不保存结果）
      elements.cancelCustomBtn?.addEventListener('click', () => this.cancel());
      
      // 卡片删除（事件委托，支持动态生成的卡片）
      elements.cardsContainer?.addEventListener('click', (e) => {
        if (e.target.classList.contains('card-delete')) {
          e.stopPropagation();
          const card = e.target.closest('.course-card');
          if (card && confirm('确定删除该课程？')) {
            const index = elements.courseCards.indexOf(card);
            if (index > -1) elements.courseCards.splice(index, 1);
            card.remove();
            filterAndSort.filterCards();
          }
        }
      });
      
      // 卡片编辑（事件委托）
      elements.cardsContainer?.addEventListener('click', (e) => {
        if (e.target.classList.contains('card-edit')) {
          e.stopPropagation();
          this.handleEditClick(e.target.closest('.course-card'));
        }
      });
      
      // 编辑表单提交
      elements.editForm?.addEventListener('submit', (e) => {
        e.preventDefault();
        this.saveEditForm();
      });
    },
    
    // 处理编辑按钮点击
    handleEditClick(card) {
      if (!card) return;
      state.currentEditingCard = card;
      
      document.getElementById('editName').value = card.querySelector('h3').textContent;
      document.getElementById('editImportance').value = utils.getElementData(card, 'importance', 3);
      document.getElementById('editCredit').value = utils.getElementData(card, 'credit', 3);
      document.getElementById('editProficiency').value = utils.getElementData(card, 'proficiency', 40);
      document.getElementById('editAi').value = utils.getElementData(card, 'ai', 2);
      document.getElementById('editStage').value = utils.getElementData(card, 'stage');
      document.getElementById('editType').value = utils.getElementData(card, 'type');
      document.getElementById('editCourseType').value = utils.getElementData(card, 'courseType');
      document.getElementById('editCommonCategory').value = utils.getElementData(card, 'commonCategory');
      document.getElementById('editIntro').value = utils.getElementData(card, 'intro', '');
      document.getElementById('editRelatedCourses').value = utils.getElementData(card, 'relatedCourses', '');
      document.getElementById('editRelatedBooks').value = utils.getElementData(card, 'relatedBooks', '');
      document.getElementById('editRelatedVideos').value = utils.getElementData(card, 'relatedVideos', '');
      
      utils.openModal(elements.modal.edit);
    },
    
    // 保存编辑表单
    saveEditForm() {
      if (!state.currentEditingCard) return;
      const card = state.currentEditingCard;
      
      // 表单数据获取
      const formData = {
        name: document.getElementById('editName').value.trim(),
        importance: document.getElementById('editImportance').value,
        credit: document.getElementById('editCredit').value,
        proficiency: parseInt(document.getElementById('editProficiency').value),
        ai: document.getElementById('editAi').value,
        stage: document.getElementById('editStage').value,
        type: document.getElementById('editType').value,
        courseType: document.getElementById('editCourseType').value,
        commonCategory: document.getElementById('editCommonCategory').value,
        intro: document.getElementById('editIntro').value.trim(),
        relatedCourses: document.getElementById('editRelatedCourses').value.trim(),
        relatedBooks: document.getElementById('editRelatedBooks').value.trim(),
        relatedVideos: document.getElementById('editRelatedVideos').value.trim()
      };
      
      // 验证
      if (isNaN(formData.proficiency) || formData.proficiency < 0) {
        alert('熟练时间必须为非负数字');
        return;
      }
      
      // 更新卡片内容
      card.querySelector('h3').textContent = formData.name;
      card.querySelector('p:nth-of-type(1)').textContent = `重要程度：${utils.generateStars(formData.importance)}`;
      card.querySelector('p:nth-of-type(2)').textContent = `学分：${formData.credit}`;
      card.querySelector('p:nth-of-type(3)').textContent = `熟练时间：${formData.proficiency}小时+`;
      card.querySelector('p:nth-of-type(4)').textContent = `AI可替代程度：${utils.generateStars(formData.ai)}`;
      
      // 更新data属性
      Object.entries(formData).forEach(([key, value]) => {
        card.dataset[key] = value;
      });
      
      utils.closeModal(elements.modal.edit);
      filterAndSort.filterCards();
    }
  };

  // ---------- 添加课程功能 ----------
  const addCourse = {
    initEvents() {
      // 打开添加课程模态框
      elements.addCourseBtn?.addEventListener('click', () => {
        utils.openModal(elements.modal.addCourse);
      });
      
      // 添加课程表单提交
      elements.addCourseForm?.addEventListener('submit', (e) => {
        e.preventDefault();
        this.handleSubmit();
      });
    },
    
    handleSubmit() {
      const name = document.getElementById('addName').value.trim();
      if (!name) {
        alert('课程名称不能为空');
        return;
      }
      
      // 获取表单数据
      const formData = {
        name,
        importance: document.getElementById('addImportance').value,
        credit: document.getElementById('addCredit').value,
        proficiency: document.getElementById('addProficiency').value,
        ai: document.getElementById('addAi').value,
        stage: document.getElementById('addStage').value,
        type: document.getElementById('addType').value,
        courseType: document.getElementById('addCourseType').value,
        commonCategory: document.getElementById('addCommonCategory').value,
        intro: document.getElementById('addIntro').value.trim(),
        relatedCourses: document.getElementById('addRelatedCourses').value.trim(),
        relatedBooks: document.getElementById('addRelatedBooks').value.trim(),
        relatedVideos: document.getElementById('addRelatedVideos').value.trim(),
        editId: utils.generateId() // 添加唯一ID用于本次编辑会话识别
      };
      
      // 创建新卡片
      const newCard = this.createCourseCard(formData);
      
      // 添加到DOM和数组
      elements.cardsContainer.appendChild(newCard);
      elements.courseCards.push(newCard);
      
      // 关闭模态框并刷新筛选
      utils.closeModal(elements.modal.addCourse);
      elements.addCourseForm.reset();
      filterAndSort.filterCards();
    },
    
    // 创建课程卡片DOM
    createCourseCard(data) {
      const card = document.createElement('div');
      card.className = 'course-card';
      
      // 设置data属性
      Object.entries(data).forEach(([key, value]) => {
        card.dataset[key] = value;
      });
      
      // 卡片内容
      card.innerHTML = `
        <span class="card-delete">×</span>
        <button class="card-edit">编辑</button>
        <h3>${data.name}</h3>
        <p>重要程度：${utils.generateStars(data.importance)}</p>
        <p>学分：${data.credit}</p>
        <p>熟练时间：${data.proficiency || 0}小时+</p>
        <p>AI可替代程度：${utils.generateStars(data.ai)}</p>
        <button class="course-detail-btn">查看详情</button>
      `;
      
      return card;
    }
  };

  // 其他功能模块（批量删除、样式设置、恢复默认、课程详情）保持不变
  // ---------- 批量删除功能 ----------
  const batchDelete = {
    initEvents() {
      // 打开批量删除模态框
      elements.batchDeleteBtn?.addEventListener('click', () => {
        utils.openModal(elements.modal.batchDelete);
        this.populateCourseSelection();
      });
      
      // 批量筛选器事件
      utils.bindEvents(
        [
          elements.batch.stageFilter,
          elements.batch.typeFilter,
          elements.batch.courseTypeFilter,
          elements.batch.commonCategoryFilter
        ],
        'change',
        () => this.populateCourseSelection()
      );
      
      // 全选/取消全选
      elements.batch.selectAllBtn?.addEventListener('click', () => {
        this.toggleAllSelection(true);
      });
      
      elements.batch.deselectAllBtn?.addEventListener('click', () => {
        this.toggleAllSelection(false);
      });
      
      // 预览删除
      elements.batch.deleteSelectedBtn?.addEventListener('click', () => {
        this.previewDelete();
      });
      
      // 确认删除
      elements.batch.confirmBatchDeleteBtn?.addEventListener('click', () => {
        this.confirmDelete();
      });
    },
    
    // 填充课程选择列表
    populateCourseSelection() {
      const container = elements.batch.customCourseSelection;
      if (!container) return;
      
      // 使用文档片段批量添加，减少DOM操作
      const fragment = document.createDocumentFragment();
      
      const stage = elements.batch.stageFilter?.value || 'all';
      const type = elements.batch.typeFilter?.value || 'all';
      const courseType = elements.batch.courseTypeFilter?.value || 'all';
      const commonCategory = elements.batch.commonCategoryFilter?.value || 'all';

      document.querySelectorAll('.course-card').forEach(card => {
        const cardStage = utils.getElementData(card, 'stage');
        const cardType = utils.getElementData(card, 'type');
        const cardCourseType = utils.getElementData(card, 'courseType');
        const cardCommonCategory = utils.getElementData(card, 'commonCategory');

        if (
          (stage === 'all' || cardStage === stage) &&
          (type === 'all' || cardType === type) &&
          (courseType === 'all' || cardCourseType === courseType) &&
          (commonCategory === 'all' || cardCommonCategory === commonCategory)
        ) {
          const item = document.createElement('div');
          item.className = 'course-item';
          item.dataset.title = card.querySelector('h3').textContent;
          item.textContent = item.dataset.title;
          item.addEventListener('click', () => item.classList.toggle('selected'));
          fragment.appendChild(item);
        }
      });
      
      container.innerHTML = '';
      container.appendChild(fragment);
    },
    
    // 全选/取消全选
    toggleAllSelection(select) {
      const items = elements.batch.customCourseSelection?.querySelectorAll('.course-item') || [];
      items.forEach(item => {
        if (select) item.classList.add('selected');
        else item.classList.remove('selected');
      });
    },
    
    // 预览删除
    previewDelete() {
      const selectedItems = elements.batch.customCourseSelection?.querySelectorAll('.course-item.selected') || [];
      const count = selectedItems.length;
      
      if (count === 0) {
        alert('请选择要删除的课程');
        return;
      }
      
      if (confirm(`预览：即将删除 ${count} 门课程（点击“保存结果”才会实际删除）`)) {
        selectedItems.forEach(item => item.classList.remove('selected'));
      }
    },
    
    // 确认删除
    confirmDelete() {
      const selectedItems = elements.batch.customCourseSelection?.querySelectorAll('.course-item.selected') || [];
      const selectedTitles = [...selectedItems].map(item => item.dataset.title);
      
      if (selectedTitles.length === 0) {
        alert('请选择要删除的课程');
        utils.closeModal(elements.modal.batchDelete);
        return;
      }

      if (confirm(`确定永久删除 ${selectedTitles.length} 门课程？`)) {
        document.querySelectorAll('.course-card').forEach(card => {
          const title = card.querySelector('h3').textContent;
          if (selectedTitles.includes(title)) {
            const index = elements.courseCards.indexOf(card);
            if (index > -1) elements.courseCards.splice(index, 1);
            card.remove();
          }
        });
        utils.closeModal(elements.modal.batchDelete);
        filterAndSort.filterCards();
      }
    }
  };

  // ---------- 样式设置功能 ----------
  const styleSetting = {
    initEvents() {
      // 打开样式设置模态框
      elements.bgColorBtn?.addEventListener('click', () => {
        this.populateCardSelection();
        utils.openModal(elements.modal.styleSetting);
      });
      
      // 保存样式设置
      document.getElementById('saveStyle')?.addEventListener('click', () => {
        this.saveStyleSettings();
      });
    },
    
    // 填充卡片选择下拉框
    populateCardSelection() {
      const select = document.getElementById('cardCourseSelect');
      if (!select) return;
      
      select.innerHTML = '';
      elements.courseCards.forEach((card, index) => {
        const option = document.createElement('option');
        option.value = index;
        option.textContent = card.querySelector('h3').textContent;
        select.appendChild(option);
      });
    },
    
    // 保存样式设置
    saveStyleSettings() {
      const container = document.querySelector('.container');
      if (!container) return;
      
      // 背景颜色设置
      const bgColor = document.getElementById('bgColor').value;
      if (bgColor) container.style.backgroundColor = bgColor;
      
      // 背景图片设置
      const bgImageInput = document.getElementById('bgImage');
      if (bgImageInput?.files?.length > 0) {
        this.handleImageUpload(bgImageInput.files[0], (url) => {
          container.style.backgroundImage = `url('${url}')`;
          container.style.backgroundSize = 'cover';
          container.style.backgroundRepeat = 'no-repeat';
          container.style.backgroundPosition = document.getElementById('bgPosition').value;
        });
      }
      
      // 卡片样式设置
      const selectedIndices = Array.from(
        document.getElementById('cardCourseSelect')?.selectedOptions || []
      ).map(opt => parseInt(opt.value));
      
      selectedIndices.forEach(index => {
        const card = elements.courseCards[index];
        if (!card) return;
        
        // 卡片边框颜色
        const borderColor = document.getElementById('cardBorderColor').value;
        if (borderColor) card.style.borderColor = borderColor;
        
        // 卡片文字颜色
        const textColor = document.getElementById('cardTextColor').value;
        if (textColor) {
          card.style.color = textColor;
          card.querySelectorAll('h3, p').forEach(el => el.style.color = textColor);
        }
        
        // 卡片背景图片
        const cardImageInput = document.getElementById('cardImage');
        if (cardImageInput?.files?.length > 0) {
          this.handleImageUpload(cardImageInput.files[0], (url) => {
            card.style.backgroundImage = `url('${url}')`;
            card.style.backgroundSize = 'cover';
            card.style.backgroundRepeat = 'no-repeat';
            card.style.backgroundPosition = document.getElementById('cardImagePosition').value;
            card.style.color = 'white';
            card.querySelectorAll('h3, p').forEach(el => el.style.color = 'white');
          });
        }
      });
      
      utils.closeModal(elements.modal.styleSetting);
    },
    
    // 处理图片上传
    handleImageUpload(file, callback) {
      const reader = new FileReader();
      reader.onload = (e) => callback(e.target.result);
      reader.onerror = () => alert('图片读取失败，请重试');
      reader.readAsDataURL(file);
    }
  };

  // ---------- 恢复默认功能 ----------
  const restoreDefault = {
    initEvents() {
      // 打开恢复默认模态框
      elements.restoreDefaultBtn?.addEventListener('click', () => {
        utils.openModal(elements.modal.restore);
      });
      
      // 全选/取消全选逻辑
      const restoreAll = document.getElementById('restoreAll');
      const checkboxes = [
        document.getElementById('restoreCourseContent'),
        document.getElementById('restoreCardTextColor'),
        document.getElementById('restoreCardBorderColor'),
        document.getElementById('restoreBackground')
      ];
      
      restoreAll?.addEventListener('change', (e) => {
        checkboxes.forEach(cb => cb.checked = e.target.checked);
      });
      
      checkboxes.forEach(cb => {
        cb?.addEventListener('change', () => {
          restoreAll.checked = checkboxes.every(c => c.checked);
        });
      });
      
      // 确认恢复
      document.getElementById('confirmRestore')?.addEventListener('click', () => {
        this.confirmRestore();
      });
    },
    
    // 确认恢复默认
    confirmRestore() {
      const container = document.querySelector('.container');
      const allCards = document.querySelectorAll('.course-card');
      
      // 恢复背景
      if (document.getElementById('restoreBackground')?.checked) {
        container.style.backgroundColor = state.persistedStyles.containerBg;
        container.style.backgroundImage = state.persistedStyles.containerBgImage;
      }
      
      // 恢复卡片边框
      if (document.getElementById('restoreCardBorderColor')?.checked) {
        allCards.forEach(card => {
          card.style.borderColor = state.persistedStyles.cardBorder;
        });
      }
      
      // 恢复卡片文字颜色
      if (document.getElementById('restoreCardTextColor')?.checked) {
        allCards.forEach(card => {
          card.style.color = state.persistedStyles.cardText;
          card.querySelectorAll('h3, p').forEach(el => {
            el.style.color = state.persistedStyles.cardText;
          });
        });
      }
      
      // 恢复课程内容
      if (document.getElementById('restoreCourseContent')?.checked) {
        elements.cardsContainer.innerHTML = '';
        elements.courseCards.length = 0;
        
        originalCards.forEach(card => {
          const clone = card.cloneNode(true);
          clone.dataset.editId = utils.generateId();
          elements.cardsContainer.appendChild(clone);
          elements.courseCards.push(clone);
        });
      }
      
      utils.closeModal(elements.modal.restore);
      filterAndSort.filterCards();
    }
  };

  // ---------- 课程详情功能 ----------
  const courseDetail = {
    initEvents() {
      // 事件委托处理详情按钮点击（支持动态卡片）
      elements.cardsContainer?.addEventListener('click', (e) => {
        if (e.target.classList.contains('course-detail-btn')) {
          const card = e.target.closest('.course-card');
          this.showDetail(card);
        }
      });
    },
    
    // 显示课程详情
    showDetail(card) {
      if (!card || !elements.modal.course) return;
      
      const title = card.querySelector('h3').textContent;
      const intro = utils.getElementData(card, 'intro', '暂无简介');
      const mindmap = utils.getElementData(card, 'mindmap', '#');
      const relatedCourses = utils.getElementData(card, 'relatedCourses', '暂无相关课程');
      const relatedBooks = utils.getElementData(card, 'relatedBooks', '暂无相关书籍');
      const relatedVideos = utils.getElementData(card, 'relatedVideos', '暂无相关视频');
      
      document.querySelector('.modal-title').textContent = title;
      document.querySelector('.modal-intro').textContent = intro;
      document.querySelector('.mindmap-link').href = mindmap;
      document.querySelector('.related-courses').textContent = relatedCourses;
      document.querySelector('.related-books').textContent = relatedBooks;
      document.querySelector('.related-videos').textContent = relatedVideos;
      
      utils.openModal(elements.modal.course);
    }
  };

  // ---------- 初始化编辑表单筛选选项 ----------
  function populateEditSelects() {
    const editSelects = [
      document.getElementById('editStage'),
      document.getElementById('editType'),
      document.getElementById('editCourseType'),
      document.getElementById('editCommonCategory')
    ];
    
    const sourceFilters = [
      elements.stageFilter,
      elements.typeFilter,
      elements.courseTypeFilter,
      elements.commonCategoryFilter
    ];
    
    editSelects.forEach((select, idx) => {
      if (!select || !sourceFilters[idx]) return;
      select.innerHTML = '';
      
      Array.from(sourceFilters[idx].options).forEach(option => {
        const newOption = document.createElement('option');
        newOption.value = option.value;
        newOption.textContent = option.textContent;
        select.appendChild(newOption);
      });
    });
  }

  // ---------- 初始化所有功能 ----------
  function init() {
    // 为初始卡片添加唯一标识
    elements.courseCards.forEach(card => {
      card.dataset.editId = utils.generateId();
    });
    
    // 初始化筛选排序
    filterAndSort.initEvents();
    
    // 初始化模态框
    modalManager.initEvents();
    
    // 初始化编辑模式
    editMode.initEvents();
    
    // 初始化添加课程
    addCourse.initEvents();
    
    // 初始化批量删除
    batchDelete.initEvents();
    
    // 初始化样式设置
    styleSetting.initEvents();
    
    // 初始化恢复默认
    restoreDefault.initEvents();
    
    // 初始化课程详情
    courseDetail.initEvents();
    
    // 填充编辑表单选项
    populateEditSelects();
    
    // 初始筛选
    filterAndSort.filterCards();
    
    // 设置默认排序
    const defaultSort = document.querySelector('.sort-option[data-sort="desc"][data-key="default"]');
    if (defaultSort) defaultSort.classList.add('active');
    
    // 初始隐藏编辑元素
    editMode.toggleEditElements(false);
    
    // 初始隐藏所有模态框
    Object.values(elements.modal).forEach(modal => {
      if (modal) modal.style.display = 'none';
    });
  }

  // 启动应用
  init();
});